<template>
	<view>
		<uni-list class="list">
			<uni-list-item @click="chooseImage" clickable class='image-list' title="头像" :showArrow="true">
				<template slot="footer">
					<image class="slot-image" :src="userInfo.icon" mode="widthFix"></image>
				</template>
			</uni-list-item>
			<uni-list-item title="性别" clickable @click="open" :rightText="genderList[userInfo.sex]" showArrow></uni-list-item>
			<picker
				mode="multiSelector" @columnchange="schoolColumnChange"
				:value="multiIndex" :range="multiArray" range-key="name" @change="changeSchool"
			>
				<view class="school-list">
					<text class="title">学校</text>
					<view class="footer">
						<view class="uni-list-item__extra">
							<text>{{userInfo.schoolName}}</text>
						</view>
						<uni-icons :size="16" class="uni-icon-wrapper" color="#bbb" type="arrowright" />
					</view>
				</view>
			</picker>
			<uni-list-item title="个人描述" clickable @click="openDesc" :rightText='userInfo.description' showArrow></uni-list-item>
		</uni-list>
		<uni-popup ref="popup" type="bottom" @change="changePopup">
			<view v-show="genderVisible" class="popup">
				<view class="popup-header">请选择你的性别</view>
				<view class="popup-content">
					<button :class="[{'active':userInfo.sex===0}]" @click="changeGender(0)">男</button>
					<button :class="[{'active':userInfo.sex===1}]" @click="changeGender(1)">女</button>
				</view>
			</view>
			<view v-show="descVisible" class="popup-wrap">
			  <view class="popup-header">
			    <text class="popup-header-item" @click="handleCancel">取消</text>
			    <text class="popup-header-item" @click="handleSubmit">确定</text>
			  </view>
			  <view class="popup-content">
			    <textarea :focus="true" class="popup-textarea" maxlength="60" v-model="commentValue" fixed placeholder="换个介绍换个心情~"></textarea>
			    <view class="popup-count">{{commentValue.length}}/60</view>
			  </view>
			</view>
		</uni-popup>
		
		<button class="exit" @click="logOut">退出账号</button>
	</view>
</template>

<script>
	import {uniList, uniListItem, uniPopup, uniIcons} from '@dcloudio/uni-ui'
	import {updateUserInfo} from '../../api/user.js'
	import {mapState, mapMutations, mapActions} from 'vuex'
	export default {
	    components: {uniList,uniListItem, uniPopup, uniIcons},
		computed:{
			...mapState(['userInfo', 'baseTarget', 'schoolData']),
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		data(){
			const currentDate = this.getDate({format: true})
			return {
				photo: '',
				genderList: ['男', '女'],
				commentValue: '',
				multiIndex: [-1, -1, -1],
				multiArray: [[], [], []],
				genderVisible: false,
				descVisible: false,
			}
		},
		onLoad(){
			this.setSchoolData().then(data=>{
				this.multiArray = [
					data, data[0].cityVOList, data[0].cityVOList[0].schoolList,
				]
			})
		},
		methods:{
			...mapActions(['setSchoolData']),
			...mapMutations({
				storeLogin: 'login',
				storeLogout: 'logout'
			}),
			bindDateChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.target.value)
				this.date = e.target.value
				this.updateUserInfo({birthday: e.target.value + ' 00:00:00'})
			},
			changePopup(e){
				if(!e.show){
					this.genderVisible = false
					this.descVisible = false
				}
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
	
				if (type === 'start') {
					year = year - 100;
					month = 1;
					day = 1;
					console.log('startDate')
				}
				return `${year}-${month}-${day}`;
			},
			schoolColumnChange(e){
				const {column, value} = e.detail
				this.multiIndex[column] = value
				switch(column){
					case 0:  // 选择的是第一列
						this.multiArray[1] = this.multiArray[0][value].cityVOList
						this.multiArray[2] = this.multiArray[1][0].schoolList
						this.multiIndex[1] = 0
						this.multiIndex[2] = 0
						break;
					case 1:  // 选择的是第二列
						this.multiArray[2] = this.multiArray[1][value].schoolList
						this.multiIndex[2] = 0
						break;
					default: break;
				}
				this.$forceUpdate()
			},
			changeSchool(e){
				console.log('change', e)
				this.multiIndex = e.detail.value
				this.updateUserInfo({schoolId: this.multiArray[2][this.multiIndex[2]].schoolId})
			},
			logOut() {
				uni.reLaunch({
					url: '/pages/login/index'
				})
				this.storeLogout()
			},
			// openChat() {
				
			// 	this.$refs.textPop.open()
			// },
			handleSubmit() {
				console.log(this.commentValue)
				this.updateUserInfo({description: this.commentValue})
				this.$refs.popup.close()
			},
			handleCancel() {
				this.$refs.popup.close()
			},
			open(){
				this.genderVisible = true
			    this.$refs.popup.open()
			},
			openDesc(){
				this.descVisible = true
				this.$refs.popup.open()
			},
			changeGender(sex){
				this.updateUserInfo({sex});
				this.$refs.popup.close()
			},
			updateUserInfo(data){
				updateUserInfo({...data, id: this.userInfo.id}).then(res=>{
					if(res.code === 200){
						this.storeLogin(res.data)
						uni.showToast({ title: "修改成功！"})
					}else{
						uni.showToast({ title: "修改失败！", icon:'none'})
					}
				})
			},
			chooseImage: async function() {
			    uni.chooseImage({
			        sourceType: ['camera','album'],
			        sizeType: ['compressed', 'original'],
			        count: 1,
			        success: (res) => {
						console.log(res)
						if(res.tempFiles[0].size > 2 * 1024 * 1000){
							uni.showToast({title: '上传的图片大小不能大于2M，请重新选择图片上传~', icon: 'none'})
							return;
						}
			            this.photo = res.tempFilePaths[0]
						this.uploadPhoto(res.tempFilePaths[0])
			        },
			        fail: (err) => {
						console.log(err)
			            // uni.getSetting({
			            //     success: (res) => {
			            //         let authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
			            //         if (!authStatus) {
			            //             uni.showModal({
			            //                 title: '授权失败',
			            //                 content: '校园美食点评需要从您的相机或相册获取图片，请在设置界面打开相关权限',
			            //                 success: (res) => {
			            //                     if (res.confirm) {
			            //                         uni.openSetting()
			            //                     }
			            //                 }
			            //             })
			            //         }
			            //     }
			            // })
			        }
			    })
			},
			uploadPhoto(photo){
				uni.showLoading({
				  title: '正在努力上传中...',
				  mask: true
				});
				console.log('要上传的文件', photo)
				uni.uploadFile({
					url: this.baseTarget + '/user/update',
					filePath: photo,
					name: 'icon',
					formData: {id: this.userInfo.id},
					success: res =>{
						if(res.data.code === 200){
							const {data} = res.data
							this.storeLogin(data)
						}else{
							uni.showToast({title: res.data.message, icon: 'none'})
						}
					},
					fail: res=>{uni.showToast({title:'我们的网络出现了一点错误，请稍候再试~', icon: 'none'})},
					complete: ()=> {uni.hideLoading()}
				})
				
			},
		}
	}
</script>

<style lang="scss">
	/* 头条、百度小程序组件内不能引入字体 */
	/* #ifdef MP-BAIDU */
	@font-face {
		font-family: uniicons;
		font-weight: normal;
		font-style: normal;
		src: url("~@/static/uni.ttf") format("truetype");
	}
	/* #endif */
	
	page{
		position: relative;
		height: 100%;
	}
	.school-list{
		display: flex;
		justify-content: space-between;
		border-top-color: #e5e5e5 solid 0.5px;
		font-size: 16px;
		position: relative;
		padding: 25rpx 0rpx 25rpx 30rpx;
		.footer{
			display: flex;
		}
		.title{
			font-size: 14px;
			color: #3b4144;
			overflow: hidden;
		}
		.uni-list-item__extra {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			justify-content: flex-end;
			align-items: center;
			color: #999;
			font-size: 12px;
		}
		&::after{
			position: absolute;
			top: 0;
			right: 0;
			left: 0;
			height: 2.5px;
			content: '';
			-webkit-transform: scaleY(0.5);
			transform: scaleY(0.5);
			background-color: #e5e5e5;
		}
	}

	.popup-wrap {
	  background-color: #ffffff;
	  .popup-header {
	    display: flex;
	    justify-content: space-between;
	    font-size: 14px;
	    color: #666;
	    border-bottom: 1px #f5f5f5 solid;
	    .popup-header-item {
	      height: 50px;
	      line-height: 50px;
	      padding: 0 15px;
	
	    }
	  }
	  .popup-content {
	    width: 100%;
	    padding: 15px;
	    box-sizing: border-box;
	    .popup-textarea {
	      width: 100%;
	      height: 200px;
	    }
	  .popup-count {
	    display: flex;
	    justify-content: flex-end;
	    color: #999;
	    font-size: 12px;
	  }
	}
	}
	.popup{
	  background-color: #fff;
	  min-height: 120px;
	  .popup-header {
	    display: flex;
	    font-size: 40rpx;
		padding: 15rpx 25rpx;
	    color: #666;
	    border-bottom: 1px #999 solid;
	  }
	  .popup-content{
		  display: flex;
		  margin-top: 30rpx;
		  justify-content: space-around;
		  .active{
			color: #ffffff;
		  	background-color: $theme-color;
			&::after{
				border: none;
			}
		  }
		  button{
		  	width: 200rpx;	
		  }
	  }
	}
	
	.list{
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}
	
	.slot-image {
		margin-right: 10px;
		width: 100rpx;
		height: 100rpx;
		// border-radius: 50rpx;
	}
	.exit {
		position: absolute;
		bottom: 30px;
		background-color: $theme-color;
		color: #FFFFFF;
		left: 50%;
		transform: translateX(-50%);
		width: 600rpx;
		// height: 30px;
		// line-height: 30px;
		font-size: 14px;
		&::after {
			border: none;
		}
	}
	.uni-icon-wrapper {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		align-items: center;
		padding: 0 10px;
	}

</style>
